package com.sjy.bloomFilter;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: ScalingBloomFilter
 * @description:
 * @author: 智慧的苏苏
 * @create: 2025-09-02 15:32
 **/
@Getter
@Setter
public class ScalingBloomFilter {
    private final double fpp; // 总体容忍误判率
    private final int initialCapacity;
    private final List<BloomFilter> filters;

    private int inserted = 0;

    public ScalingBloomFilter(int initialCapacity, double fpp) {
        this.initialCapacity = initialCapacity;
        this.fpp = fpp;
        this.filters = new ArrayList<>();
        // 初始化第一个 filter
        filters.add(new BloomFilter(initialCapacity, fpp));
    }

    /**
     * 添加元素
     */
    public void add(Object element) {
        BloomFilter current = filters.get(filters.size() - 1);

        // 判断是否超出容量 -> 扩容
        if (inserted >= (filters.size() * initialCapacity)) {
            // 新增一个更大的 filter，容量翻倍，误判率可以保持
            int newCapacity = initialCapacity * (1 << (filters.size() - 1));
            filters.add(new BloomFilter(newCapacity, fpp));
            current = filters.get(filters.size() - 1);
        }

        current.add(element);
        inserted++;
    }

    public boolean isExist(Object element) {
        for (BloomFilter filter : filters) {
            if (filter.isExist(element)) {
                return true;
            }
        }
        return false;
    }

}
